package com.ruoyi.framework.service;

import com.google.code.kaptcha.Producer;
import com.ruoyi.common.constant.Constants;

import com.ruoyi.common.entity.LoginUser;
import com.ruoyi.common.entity.system.SysUser;
import com.ruoyi.common.enums.ExceptionEnum;
import com.ruoyi.common.exception.BizException;
import com.ruoyi.common.util.DateUtils;
import com.ruoyi.common.util.RedisUtil;
import com.ruoyi.common.util.ServletUtils;
import com.ruoyi.common.util.ip.IpUtils;

import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import sun.misc.MessageUtils;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 * 
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private Producer producer;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;
    
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 登录验证
     * 
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validate(uuid,code);
        }
        // 用户验证
        Authentication authentication;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                //AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new BizException(ExceptionEnum.LOGIN_FAIL,"用户名或者密码错误");
            } else {
                //AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new RuntimeException(e.getMessage());
            }

        }
        //AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUser());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 记录用户登录信息
     */
    public void recordLoginInfo(SysUser user) {
        user.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        user.setLoginDate(DateUtils.getNowDate());
        userService.updateById(user);
    }

    /**
     * 获取验证码图片
     * @param uuid uuid
     * @return BufferedImage
     */
    public BufferedImage getCode(String uuid) {
        //验证uuid不能为空
        if (StringUtils.isBlank(uuid)){
            throw new BizException(ExceptionEnum.ERROR,"uuid不能为空");
        }
        //生成文字验证码
        String code=producer.createText();
        //验证码存入redis 5分钟内有效
        redisUtil.set(Constants.SYS_CODE+uuid,code,5, TimeUnit.MINUTES);

        return producer.createImage(code);
    }

    /**
     * 校验验证码
     * @param uuid uuid
     * @param captcha code
     */
    public void validate(String uuid, String captcha) {
        //先从redis中获取验证码
        String code= (String) redisUtil.get(Constants.SYS_CODE+uuid);
        //删除验证码缓存
        redisUtil.del(Constants.SYS_CODE);
        if (Objects.isNull(code)){
            //说明该验证码不存在或者已经过期
           throw new BizException(ExceptionEnum.LOGIN_FAIL,"验证码已过期");
        }
        if (!captcha.equalsIgnoreCase(code)){
            //说明不相等
            throw new BizException(ExceptionEnum.LOGIN_FAIL,"验证码错误");
        }
    }
}
